package chances.epg.data.taglib;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.URLUtils;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.content.CategoryItem;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.context.AccessContextUtils;


/**
 * 编排列表.
 * 支持分页查询.
 * @author Elysium
 *
 */
public class CategoryItemScheduleTag extends QueryListTag {
	private static final Logger logger = EpgLogFactory.getSystemLogger();
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = -1206180657029929973L;
	private String code;//栏目编码
	
	private int size = 10;//条目数
	private String isparent = "false";//是否根据parent栏目查询编排
	private String type="all";//past,play,next,all,location
    private String random = "false";//是否随机
	
	@Override
	public int doEndTag() throws JspException {
		String categoryCode = this.code;
		if(StringUtils.isBlank(categoryCode)){
			categoryCode = this.getCurCategoryCode();
		}
		
		if(StringUtils.isBlank(categoryCode)){
			return super.doEndTag();
		}
		
		try{
            if("true".equals(this.getRandom())){
                this.queryRandomItem(categoryCode,isByParentCategory());
            }else if(StringUtils.isNotBlank(this.getPageName())){
				this.queryItemByPage(categoryCode,isByParentCategory());
			}else{
				this.queryItemBySize(categoryCode,isByParentCategory());
			}
		}catch(Throwable ex){
			logger.error("CategoryScheduleItemTag error",ex);
		}
		
		return super.doEndTag();
	}
	   
    /**
     * 按照指定数量随机获取.
     */
    private void queryRandomItem(String categoryCode,boolean byParent){
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("categoryCode", categoryCode);
        paramsMap.put("itemType", "schedule"); 
        paramsMap.put("curTime", new Date()); 
        if(byParent){
            paramsMap.put("byParent", byParent); 
        }
        
        List<CategoryItem> result = null;
        if(type.equals("past")){
            result = this.getChannelService().getCategoryItemPastSchedule(paramsMap,0,500);
        }else if (type.equals("play")) {
            result = this.getChannelService().getCategoryItemPlaySchedule(paramsMap,0,500);
        }else if (type.equals("all")) {
            result = this.getChannelService().getCategoryItemSchedule(paramsMap,0,500);
        }
        
        if(result.size() <= this.size){
            this.setAttribute(this.getVar(), result);
        }else{
            List<CategoryItem> randomResult = new ArrayList<CategoryItem>();
            int[] randomSequence = this.getRandomSequence(result.size());
            for (int i = 0; i < this.size; i++) {
                randomResult.add(result.get(randomSequence[i]));
            }
            
            this.setCategoryItem(randomResult);
        }
    }
	
	/**
	 * 分页查询.
	 */
	private void queryItemByPage(String categoryCode,boolean byParent) {
		PageInfo pageInfo = this.createPageInfo(size);
		
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("categoryCode", categoryCode);
        paramsMap.put("curTime", new Date()); 
        if(byParent){
            paramsMap.put("byParent", byParent); 
        }
        
        List<CategoryItem> result = null;
        if(type.equals("past")){
            result = this.getChannelService().getCategoryItemPastSchedule(paramsMap, this.start,pageInfo.getPageBean());
        }else if (type.equals("play")) {
            result = this.getChannelService().getCategoryItemPlaySchedule(paramsMap, this.start,pageInfo.getPageBean());
        }else if (type.equals("all")) {
            result = this.getChannelService().getCategoryItemSchedule(paramsMap, this.start,pageInfo.getPageBean());
        }
		this.setPageInfo(pageInfo);
		this.setCategoryItem(result);
	}
	
	/**
	 * 查询指定数量的条目.
	 */
	private void queryItemBySize(String categoryCode,boolean byParent) {
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("categoryCode", categoryCode);
        paramsMap.put("curTime", new Date());       
        if(byParent){
            paramsMap.put("byParent", byParent); 
        }
        
		List<CategoryItem> result = null;
        if(type.equals("past")){
            result = this.getChannelService().getCategoryItemPastSchedule(paramsMap,this.start,this.size);
        }else if (type.equals("play")) {
            result = this.getChannelService().getCategoryItemPlaySchedule(paramsMap,this.start,this.size);
        }else if (type.equals("all")) {
            result = this.getChannelService().getCategoryItemSchedule(paramsMap,this.start,this.size);
        }
        this.setCategoryItem(result);
	}
	
	/**
	 * 
	 * @param result
	 */
    private void setCategoryItem(List<CategoryItem> result) {
        int index = 0;
        AccessContext context = AccessContextUtils
                .getAccessContext(pageContext);
        if (null != context) {
            for (CategoryItem categoryItem : result) {
                index++;
                String url = navigateUrlFactory.generateURL(context,
                        categoryItem);
                url = URLUtils.appendParam(url, "pi", index + "");
                categoryItem.setUrl(url);
            }
        }

        this.setCollectionResult(result);
    }
    
    /**
     * 生成随机序列.
     * @param total
     * @return
     */
    private int[] getRandomSequence(int total)
    {
        int[] sequence = new int[total];
        int[] output = new int[total];

        for (int i = 0; i < total; i++)
        {
            sequence[i] = i;
        }
        
        int end = total - 1;

        for (int i = 0; i < total; i++)
        {
            int num = RandomUtils.nextInt(end+1);
            output[i] = sequence[num];
            sequence[num] = sequence[end];
            end--;
        }

        return output;
    }
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	
	/**
	 * 是否根据父栏目.
	 * @return
	 */
	public boolean isByParentCategory() {
		if("true".equals(this.isparent)){
			return true;
		}else{
			return false;
		}
	}

	public String getIsparent() {
		return isparent;
	}

	public void setIsparent(String isparent) {
		this.isparent = isparent;
	}

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getRandom() {
        return random;
    }

    public void setRandom(String random) {
        this.random = random;
    }
}
